package cn.davidsu.library.util;

import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;

public class Util {

    public static int vp2px(Context context, float vpValue) {
        float scale = context.getResourceManager().getDeviceCapability().screenDensity/160f;
        return (int) (vpValue*scale);
    }

    public static int toIntegerValue(String res){
        try {
            if (res==null)return -1;
            int index = res.indexOf(":")+1;
            String value = res.substring(index);
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    /**
     * 获取颜色
     * @param value
     * @return
     */
    public static int parseColorFromString(Context context, String value, int defaultColor) {
        if (TextTool.isNullOrEmpty(value))return defaultColor;
        if (value.startsWith("$")){
            try {
                return context.getResourceManager().getElement(toIntegerValue(value)).getColor();
            } catch (Exception e) {
                LogUtil.i("error msg: %s", e.getLocalizedMessage());
            }
        }
        if (value.length() == 7) {
            value = value.replace("#", "#ff");
        } else if (value.length() == 4) {
            value = String.format("#ff%1$c%1$c%2$c%2$c%3$c%3$c", value.charAt(1), value.charAt(2), value.charAt(3));
        } else if (value.length() == 2) {
            value = String.format("#ff%1$c%1$c%1$c%1$c%1$c%1$c", value.charAt(1));
        }
        return value.length() == 9 ? parseColor(value) : defaultColor;
    }

    private static int parseColor(String colorString){
        int alpha = Integer.parseInt(String.format("%c%c", colorString.charAt(1), colorString.charAt(2)), 16);
        int rgb = Integer.parseInt(colorString.substring(3).toLowerCase(), 16);
        return alpha<<24|rgb;
    }
}
